<template>
  <a-spin size="large" tip="提交中..." :spinning="loading">
    <title-info>
      <a-button class="label" type="warning" @click="Data.restoreVisible = 'YJ'">
        <retweet-outlined class="mr-1" /> 调阅原卷
      </a-button>
      <a-button class="label" type="primary" @click="Data.restoreVisible = 'DTK'">
        <retweet-outlined class="mr-1" /> 调阅答题卡
      </a-button>
      <a-button type="danger" class="label" @click="openModel('abnormalVisible')">
        <exclamation-circle-outlined class="mr-1" /> 标记异常
      </a-button>
      <div class="line label"></div>
    </title-info>
    <div class="container-wrap">
      <canvas-container
        :prpopsStyle="{
          width: '65%',
          height: '100%',
          marginRight: '20px',
        }"
        ref="canvasRef"
        :imgList="currentTopic.dtkqtxxVoList || []"
        :recordClick="recordClick"
        :questionsInfo="questionsInfo"
      >
        <template #standardmodule="{ scale, imgInfo }" v-if="Data.dtkType && Data.dtkType.length">
          <standard-modeule
            :onelyShow="false"
            :scale="scale"
            :imgInfo="imgInfo"
            :result="Data.dtkType || []"
          />
        </template>
      </canvas-container>

      <choie-quiz-ques></choie-quiz-ques>
    </div>

    <!-- 答题卡还原 -->
    <restore-card
      v-model:restoreVisible="Data.restoreVisible"
      :pyZycId="questionsInfo.pyZycId || questionsInfo.pyZycIdList[0]"
      :kmdm="(route.query?.kmdm as string)"
    />

    <!-- 退出评阅 -->
    <sele-option-topic
      v-model:seleopti-bloon="Data.seleoptiBloon"
      :seleOptions="Data.seleOptions"
      :seleOptiTitle="Data.seleOptiTitle"
      :isJdType="true"
    />
    <!-- 标记异常弹窗 -->
    <abnormal-modal
      v-model:abnormal-visible="Data.abnormalVisible"
      :questionsInfo="{
        ...questionsInfo,
        kmdm: route.query.kmdm,
      }"
      :ycSource="questionsInfo.value?.pyZycIdList ? 'CP' : undefined"
      :pyKssj="startTime"
      :pyTjsj="dayjs().format('YYYY-MM-DD HH:mm:ss')"
    />
  </a-spin>
</template>

<script lang="ts" setup>
import titleInfo from '../review/components/titleInfo.vue'
import choieQuizQues from './components/choieQuizQues.vue'
import standardModeule from './components/standardModeule.vue'
import CanvasContainer from '/@/layouts/components/CanvasChart/canvasContainer.vue'
import abnormalModal from '/@/views/teacher/review/components/abnormal.vue'
import seleOptionTopic from '/@/views/teacher/review/components/seleOptionTopic.vue'
import restoreCard from '/@/views/teacher/review/restoreCard.vue'

import { isJdWrongType } from '/@/views/examination-audit/abnormal-teacher/index'

import { computed, onMounted, watch, reactive, ref } from 'vue'
import dayjs from 'dayjs'
import {
  getExtractZycKgt,
  getZycwatchPaperCheck,
  myReviewWork,
  getCpDataByAccount,
  getDtkTypeByPyZycId,
} from '/@/api/teacher'
import { showPaper } from '/@/api/organization/examinationPaper'

import { useMessage } from '/@/hooks/web/useMessage'
const { createMessage } = useMessage()

import { useRoute, useRouter } from 'vue-router'
const route = useRoute()
const router = useRouter()

const Data = reactive({
  restoreVisible: '',
  seleoptiBloon: false,
  seleOptions: [],
  seleOptiTitle: '',
  abnormalVisible: false,
  dtkType: [],
})

const canvasRef = ref<any>()

import { useTeacherMarkStore } from '/@/store/modules/teacherMark'
const teacherMarkStore = useTeacherMarkStore()
const questionsInfo = computed(() => teacherMarkStore.getQuestions)
const currentTopic = computed(() => teacherMarkStore.getCurrentTopic ?? {})
const isNext = computed(() => teacherMarkStore.getNext)
const loading = computed(() => teacherMarkStore.getLoading)

import { useUserStore } from '/@/store/modules/user'
const userStore = useUserStore()
const startTime: any = computed(() => userStore.getStartTime)
const addSubjectForm = computed(() => userStore.getSysConfig)

// 是否需要点击图片
const recordClick = computed(() => {
  if (!questionsInfo.value.pyZycIdList && addSubjectForm.value.clickDtkqtCheck4KgtFlag) return true
  return false
})

// 开启弹窗
function openModel(type: string): void {
  Data[type] = true
}

// 返回上一页
const pageGoBack = () => {
  router.back()
}

// 抽题
async function checkGetExtractZycKgt() {
  const { code, data, message } = await getExtractZycKgt({
    kmdm: route.query.kmdm,
    stId: questionsInfo.value.stId,
  })
  if (code == 200) {
    if (data) {
      teacherMarkStore.setQuestions(data)
      getPageInfoFun()
    }
  } else if (code == 8104 || code == 8103) {
    // 当前题型已经没有试题了
    teacherMarkStore.setLoading(false)
    getOtherQuestionTyp(message)
    return
  } else {
    createMessage.error(message)
    pageGoBack()
  }
}

// 获取重评题列表
const getTodoDaYcXxE = async () => {
  let { code, data } = await getCpDataByAccount({
    kmdm: route.query.kmdm,
  })
  if (code == 200 && data?.length) {
    for (let i = 0; i < data.length; i++) {
      if (data[i].stId == questionsInfo.value.stId) {
        teacherMarkStore.setQuestions(data[i])
        return getPageInfoFun()
      }
    }
    getOtherQuestionTyp('当前题型重评题已完成')
  } else {
    getOtherQuestionTyp('重评题已完成')
  }
}

// 当前题型没有试题操作
const getOtherQuestionTyp = async e => {
  let { code, data } = await myReviewWork({}).catch(err => {
    createMessage.success(e)
    // 抽题失败 回到首页
    pageGoBack()
  })
  if ((code == 200 && data && data.length) || e === '当前题型重评题已完成') {
    Data.seleOptions = data
    Data.seleOptiTitle = e
    openModel('seleoptiBloon')
    // message 无可评阅资源；
  } else {
    createMessage.success(e)
    // 抽题失败 回到首页
    pageGoBack()
  }
}

// 获取切片数据识别信息
async function isExamPaper(todoList: string[] = []) {
  const { code, data } = await getDtkTypeByPyZycId({
    todoList,
  })
  if (code == 200) {
    if (data.length) {
      Data.dtkType = data.filter(el => {
        el.sbdjgList = el.sbjg?.split(',')
        el.xxdwzList = el.xxwz?.slice(1, el.xxwz.length - 1)?.split('),(')
        for (let i = 0; currentTopic.value.ckdaInfoList.length > i; i++) {
          let item = currentTopic.value.ckdaInfoList[i]
          if (item.stId == el.tmid) {
            for (let i = 0; i < el.sbdjgList?.length; i++) {
              if (el.sbdjgList[i] === '1') {
                if (currentTopic.value.tmlx == '判断题') {
                  if (i === 0) {
                    item.setCkda.push('true')
                  } else {
                    item.setCkda.push('false')
                  }
                } else {
                  item.setCkda.push(String.fromCharCode(65 + i))
                }
              }
            }
            let arr = item.ckda.split(',')
            el.ckda = new Array(item.xxsl || 2).fill('0')
            for (let i = 0; i < arr.length; i++) {
              if (currentTopic.value.tmlx == '判断题') {
                arr[i] === 'true' && (el.ckda[0] = '1')
                arr[i] === 'false' && (el.ckda[1] = '1')
              } else {
                el.ckda[arr[i].charCodeAt(0) - 65] = '1'
              }
            }
            if (!item.setCkda.length) {
              item.setCkda = ['Z']
            }
            item.pyDa = item.setCkda.join(',')
            return true
          }
        }
      })
    }

    // Data.dtkType = data
  }
}

// 获取题目数据
const getPageInfoFun = async () => {
  teacherMarkStore.setLoading(true)
  const { data, code, message } = await getZycwatchPaperCheck({
    kmdm: route.query.kmdm,
    pyZycId: questionsInfo.value.pyZycId || questionsInfo.value.pyZycIdList[0],
    stId: questionsInfo.value.stId,
  })
  if (code == 200 && data) {
    data.ckdaInfoList
      .sort((a, b) => a.tmxh - b.tmxh)
      .forEach(item => {
        if (data.tmlx == '判断题') {
          item.radioLength = isJdWrongType.slice(isJdWrongType.length - 2)
        } else {
          item.radioLength = isJdWrongType.slice(0, item.xxsl)
        }
        item.setCkda = []
        item.radioLength.push({
          label: '未作答',
          value: 'Z',
        })
      })

    teacherMarkStore.setCurrentTopic(data)
    if (!data.dtkqtxxVoList?.length) {
      getIMgLis()
    } else {
      isExamPaper(data.dtkqtxxVoList.map(el => el.id) || [])
    }
    userStore.setStartTime(dayjs().format('YYYY-MM-DD HH:mm:ss'))
  } else {
    createMessage.error(message)
    // 抽题失败 回到首页
    pageGoBack()
  }
  teacherMarkStore.setLoading(false)
}

/**
 * 获取图片列表
 */
const getIMgLis = async () => {
  const { data, code } = await showPaper({
    pyZycId: questionsInfo.value.pyZycId || questionsInfo.value.pyZycIdList[0],
  })
  if (code == 200) {
    currentTopic.value.dtkqtxxVoList = data
  }
  if (!data.length) {
    createMessage.error('当前试卷没有获取到图片')
  }
}

watch(
  () => isNext.value,
  async val => {
    if (val) {
      teacherMarkStore.setLoading(true)
      canvasRef.value.restoration()
      if (questionsInfo.value.pyZycIdList) {
        //重评题
        getTodoDaYcXxE()
      } else {
        // 上次未完成的抽题 // 重新抽题
        await checkGetExtractZycKgt()
      }
      teacherMarkStore.setNext(false)
    }
  }
)

onMounted(async () => {
  if (questionsInfo.value.pyZycIdList) {
    //重评题
    getTodoDaYcXxE()
  } else {
    // 上次未完成的抽题 // 重新抽题
    await checkGetExtractZycKgt()
  }
})
</script>
<style lang="less" scoped>
.label {
  cursor: pointer;
  margin-right: 16px;
  margin-left: 5px;
  font-weight: 700;
}

.line {
  height: 20%;
  width: 1px;
  margin: 0 20px;
  background: #dddada;
}

.container-wrap {
  width: 100%;
  display: flex;
  height: calc(100vh - 90px);
}
</style>
